package com.tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Properties;

/**
 * @author lemonjesnme
 *
 */
public class Perl {
	public static String JavaUsePerl(String perlexePath, String perlFilePath, String cmdParam1, String cmdParam2) {
		String[] cmd = { perlexePath, perlFilePath, cmdParam1, cmdParam2 };
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		Process ps;
		try {
			ps = Runtime.getRuntime().exec(cmd);
			InputStream inputStream = ps.getInputStream();
			byte b;
			while ((b = (byte) inputStream.read()) != -1) {
				baos.write(b);
			}
		} catch (IOException e) {
			System.out.println("java use perl failed!");
		}
		return baos.toString();
	}

	public static Properties getEnv() throws Exception {
		Properties prop = new Properties();
		String OS = System.getProperty("os.name").toLowerCase();
		Process p = null;
		if (OS.indexOf("windows") > -1) {
			p = Runtime.getRuntime().exec("cmd /c set");
		}
		if (OS.indexOf("linux") > -1) {
			p = Runtime.getRuntime().exec("sh -c set");
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
		String line;
		while ((line = br.readLine()) != null) {
			int i = line.indexOf("=");
			if (i > -1) {
				String key = line.substring(0, i);
				String value = line.substring(i + 1);
				prop.setProperty(key, value);
			}
		}
		return prop;
	}

	public static String getPerlexePath() {
		Properties p = null;
		try {
			p = getEnv();
		} catch (Exception e) {
			System.out.println(System.err);
		}
		String path = p.getProperty("Path");
		int e = path.indexOf("\\Perl\\bin;");
		path = path.substring(0, e);
		int i = path.indexOf(";");
		if (i != -1) {
			path = path.substring(path.lastIndexOf(";") + 1);
		}
		return path + "\\perl\\bin\\perl.exe";
	}

	public static String getDataFilePath(String rlt) {
		File filedir = new File("data");
		filedir.mkdirs();

		File file = new File(".\\data\\1.txt");
		if (file.exists()) {
			file.delete();
		}
		try {
			file.createNewFile();
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
			out.print(rlt);
			out.close();
		} catch (IOException e) {
			System.out.println(System.err);
		}
		String path = file.getAbsolutePath();
		path = file.getPath();
		return path;
	}
}
